package com.roamer.school.common.exception;

import com.roamer.school.common.Assert;
import com.roamer.school.common.exception.enums.ExceptionEnum;
import com.roamer.school.common.exception.enums.ResultCode;
import com.roamer.school.common.util.StringUtils;
import lombok.Data;
import lombok.EqualsAndHashCode;

import javax.validation.constraints.NotNull;

/**
 * 业务异常类
 *
 * @author roamer
 * @version V1.0
 * @date 2019/1/20 20:09
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class BusinessException extends RuntimeException {

    private static final long serialVersionUID = -8464756557217304892L;

    protected String code;

    protected String message;

    protected ResultCode resultCode;

    protected Object data;

    public BusinessException() {
        ExceptionEnum exceptionEnum = ExceptionEnum.getByExceptionClass(this.getClass());
        if (exceptionEnum != null) {
            resultCode = exceptionEnum.getResultCode();
            code = exceptionEnum.getResultCode().getCode().toString();
            message = exceptionEnum.getResultCode().getMessage();
        }

    }

    public BusinessException(String message) {
        this();
        this.message = message;
    }

    public BusinessException(String format, Object... objects) {
        this();
        format = StringUtils.replace(format, "{}", "%s");
        this.message = String.format(format, objects);
    }

    public BusinessException(String msg, Throwable cause, Object... objects) {
        this();
        String format = StringUtils.replace(msg, "{}", "%s");
        this.message = String.format(format, objects);
    }

    public BusinessException(ResultCode resultCode, Object data) {
        this(resultCode);
        this.data = data;
    }

    public BusinessException(@NotNull ResultCode resultCode) {
        Assert.isNotNull(resultCode, "resultCode is cannot null");
        this.resultCode = resultCode;
        this.code = resultCode.getCode().toString();
        this.message = resultCode.getMessage();
    }

}
